//
//  CAAnimation+SpringAnimation.m
//  SpringAnimation
//
//  Created by Hanjun Hong on 15/9/9.
//  Copyright (c) 2015年 Anyfish. All rights reserved.
//

#import "CAAnimation+SpringAnimation.h"

@implementation CAAnimation (SpringAnimation)
+ (CAKeyframeAnimation *)springAnimationDuration:(NSTimeInterval)duration
                                           delay:(NSTimeInterval)delay
                                         damping:(CGFloat)dampingRatio
                                        velocity:(CGFloat)velocity
                                       fromValue:(id)fromValue
                                         toValue:(id)toValue
                                      forKeyPath:(NSString *)keyPath {
    dampingRatio *= 10;
    velocity *= 10;
    //每秒60个关键帧
    int frameCounts  = duration * 60;
    NSMutableArray *values = [NSMutableArray array];
    //起点、结束终值差距
    CGFloat diff = [toValue floatValue] - [fromValue floatValue];
    //计算60个关键帧的值
    for (int frameIndex = 0; frameIndex<frameCounts; frameIndex++) {
        CGFloat x = (CGFloat)frameIndex / (CGFloat)frameCounts;
        CGFloat value = [toValue floatValue] - diff * (pow(M_E, -dampingRatio * x) * cos(velocity * x));
        // y = 1-e^{-5x} * cos(30x)
        [values addObject:@(value)];
    }
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:keyPath];
    animation.beginTime = CACurrentMediaTime() + delay;
    animation.values = values;
    animation.duration = duration;
    animation.fillMode = kCAFillModeForwards;
    animation.removedOnCompletion = NO;
    return animation;
}
@end
